import React, { PureComponent } from 'react';
import { DownOutlined, PlusOutlined, UpOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Card, Col, Row, Button, Input, message, Badge, Modal, Divider } from 'antd';
import moment from 'moment';
import { connect } from 'dva';
import router from 'umi/router';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import StandardTable from '@/components/StandardTable';
import TextOverFlow from '../../components/TextOverFlow';
import styles from '@/utils/utils.less';
import Customer from '../../components/Customer';
import DictCode from '../../components/DictCode';
import downloadFile from '@/utils/utils';
import SearchPersonEs from '../../components/SearchPersonEs';

const FormItem = Form.Item;
const { confirm } = Modal;
@connect(({ issueprove, loading }) => ({
  loading: loading.models.issueprove,
  pageData: issueprove.pageData,
  formFieldsValue: issueprove.formFieldsValue,
  expandForm: issueprove.expandForm,
}))
@Form.create()
class IssueProve extends PureComponent {
  state = {
    selectedRows: [],
    selectedRowKeys: [],
    stateMap: ['', 'success', 'default'], // 第一项用success
  };

  tableSearchLayout = {
    labelCol: { md: { span: 7 } },
    wrapperCol: { md: { span: 17 } },
  };

  componentDidMount = () => {
    const {
      pageData: { pagination },
      location,
    } = this.props;
    const { isMenuLink } = location.query;
    if (isMenuLink) {
      this.resetAndGeLlist(location);
    } else {
      this.getList(pagination.current, pagination.pageSize);
    }
  };

  // 查询
  getList = (currentPage = 1, pageSize = 10, isClear = true) => {
    const { dispatch, form } = this.props;
    if (isClear) {
      this.setState({
        selectedRows: [],
        selectedRowKeys: [],
      });
    }
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      dispatch({
        type: 'issueprove/updateModelData',
        payload: { formFieldsValue: fieldsValue },
      });
      const formFieldsValue = {};
      Object.keys(fieldsValue).forEach(key => {
        formFieldsValue[key] = fieldsValue[key] === undefined ? null : fieldsValue[key].trim();
      });
      const pageArg = { currentPage, pageSize };
      const values = {
        ...formFieldsValue,
        pageArg,
      };
      dispatch({
        type: 'issueprove/fetchList',
        payload: {
          ...values,
        },
      });
    });
  };

  downExcel = () => {
    const { pageData, form } = this.props;
    const { selectedRowKeys } = this.state;
    const {
      pagination: { total },
    } = pageData;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const formFieldsValue = {};
      Object.keys(fieldsValue).forEach(key => {
        formFieldsValue[key] = fieldsValue[key] === undefined ? null : fieldsValue[key].trim();
      });
      if (Number(total) === 0) {
        message.warning('无查询结果，不可导出');
      } else {
        downloadFile(
          { ...formFieldsValue, proveSerHdlIds: selectedRowKeys },
          '/esApi/proveHdl/export',
          'POST'
        );
      }
    });
  };

  // 导出
  outExcel = () => {
    const { selectedRowKeys } = this.state;
    if (selectedRowKeys.length) {
      this.setState({
        excelLoading: true,
      });
      downloadFile({ proveSerHdlIds: selectedRowKeys }, '/esApi/proveHdl/export', 'POST', () => {
        this.setState({
          excelLoading: false,
        });
      });
    } else {
      confirm({
        title: `如果不选择数据，则默认导出当前列表下所有数据`,
        icon: <QuestionCircleOutlined />,
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          this.downExcel();
        },
      });
    }
  };

  // 删除
  canceldeal = () => {
    const { dispatch } = this.props;
    const { selectedRows } = this.state;
    const canceldealArr = [];
    const values = {};
    if (selectedRows.length) {
      selectedRows.map(item => {
        const obj = {};
        obj.proveSerHdlId = item.proveSerHdlId;
        obj.vno = item.vno;
        canceldealArr.push(obj);
        return true;
      });
      values.list = canceldealArr;
      confirm({
        title: '您确定要删除吗？',
        okText: '确定',
        icon: <QuestionCircleOutlined />,
        okType: 'danger',
        cancelText: '取消',
        onOk: () => {
          dispatch({
            type: 'issueprove/deleteData',
            payload: {
              ...values,
            },
          });
        },
      });
    } else {
      message.warning('至少选择一条数据');
    }
  };

  // 重置
  resetSearch = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    dispatch({
      type: 'issueprove/updateModelData',
      payload: { formFieldsValue: {} },
    });
  };

  toggleForm = () => {
    const { expandForm, dispatch } = this.props;
    dispatch({
      type: 'issueprove/updateModelData',
      payload: { expandForm: !expandForm },
    });
  };

  // 点击复选框
  handleSelectRows = (selectedRows, selectedRowKeys) => {
    this.setState({ selectedRows, selectedRowKeys });
  };

  // 表格有变化：比如：切换页码
  handleStandardTableChange = pagination => {
    this.getList(pagination.current, pagination.pageSize, false);
  };

  // 重置查询条件并获取列表
  async resetAndGeLlist(location) {
    await this.resetSearch();
    await this.getList();
    const { dispatch } = this.props;
    dispatch({
      type: 'issueprove/updateModelData',
      payload: { expandForm: false },
    });
    dispatch({
      type: 'global/changeIsMenuLink',
      payload: location,
    });
  }

  renderAdvancedForm() {
    const {
      form: { getFieldDecorator },
      formFieldsValue,
    } = this.props;

    return (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="姓名" {...this.tableSearchLayout}>
              {getFieldDecorator('empName', {
                initialValue: formFieldsValue.empName,
              })(<Input placeholder="请输入姓名" maxLength={15} />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="证件号" {...this.tableSearchLayout}>
              {getFieldDecorator('certNo', {
                initialValue: formFieldsValue.certNo,
              })(<Input placeholder="请输入证件号" maxLength={18} />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="证明类型" {...this.tableSearchLayout}>
              {getFieldDecorator('proveType', {
                initialValue: formFieldsValue.proveType,
              })(
                <DictCode
                  dictType="PROVE_TYPE"
                  allowClear
                  showSearch
                  filterOption={(input, option) =>
                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }
                />
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="客户名称" {...this.tableSearchLayout}>
              {getFieldDecorator('custId', {
                initialValue: formFieldsValue.custId,
              })(
                <Customer
                  attr
                  allowClear
                  showSearch
                  filterOption={(input, option) =>
                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }
                />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="办理人" {...this.tableSearchLayout}>
              {getFieldDecorator('hdlName', {
                initialValue: formFieldsValue.hdlName,
              })(
                <SearchPersonEs
                  allowClear
                  showSearch
                  filterOption={(input, option) =>
                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }
                />
              )}
            </FormItem>
          </Col>
          <Col>
            <div style={{ float: 'right', marginBottom: 24 }}>
              <Button type="primary" htmlType="submit" onClick={() => this.getList()}>
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                重置
              </Button>
              <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                收起 <UpOutlined />
              </a>
            </div>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    const { expandForm } = this.props;
    return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  }

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
      formFieldsValue,
    } = this.props;
    return (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="姓名" {...this.tableSearchLayout}>
              {getFieldDecorator('empName', {
                initialValue: formFieldsValue.empName,
              })(<Input placeholder="请输入姓名" maxLength={15} />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="证件号" {...this.tableSearchLayout}>
              {getFieldDecorator('certNo', {
                initialValue: formFieldsValue.certNo,
              })(<Input placeholder="请输入证件号" maxLength={18} />)}
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit" onClick={() => this.getList()}>
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                重置
              </Button>
              <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                展开 <DownOutlined />
              </a>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  render() {
    const { pageData, loading } = this.props;
    const { selectedRows, selectedRowKeys, stateMap, excelLoading } = this.state;

    const columns = [
      {
        title: '姓名',
        dataIndex: 'empName',
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
          },
        }),
      },
      {
        title: '证件号',
        dataIndex: 'certNo',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'center', width: 170 } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
      },
      {
        title: '客户名称',
        dataIndex: 'custName',
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
          },
        }),
        render: text => <TextOverFlow text={text} />,
      },

      {
        title: '证明类型',
        dataIndex: 'proveTypeName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
      },
      {
        title: '状态',
        dataIndex: 'stateName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: (text, record) =>
          record.stateName ? (
            <Badge key={record.state} status={stateMap[record.state]} text={record.stateName} />
          ) : (
            '--'
          ),
      },
      {
        title: '办理人',
        dataIndex: 'operName',
        onHeaderCell: () => ({
          style: {
            fontWeight: 'bold',
          },
        }),
      },
      {
        title: '操作时间',
        dataIndex: 'operTime',
        sorter: (a, b) => new Date(b.creTime) - new Date(a.creTime),
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: val => (val ? moment(val).format('YYYY-MM-DD HH:mm') : '--'),
      },
      {
        title: '操作',
        dataIndex: 'operation',
        width: 120,
        onHeaderCell: () => ({ style: { fontWeight: 'bold', textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: (text, record) => (
          <span>
            {Number(record.state) === 1 ? null : (
              <span>
                <a
                  onClick={() =>
                    router.push(`/hrmanage/issueproof/update?id=${record.proveSerHdlId}`)
                  }
                >
                  修改
                </a>
                <Divider type="vertical" />
              </span>
            )}

            <a
              onClick={() => router.push(`/hrmanage/issueproof/detail?id=${record.proveSerHdlId}`)}
            >
              查看
            </a>
          </span>
        ),
      },
    ];

    return (
      <PageHeaderWrapper>
        <Card className={styles.searchCard}>
          <div className={styles.tableListForm}>{this.renderForm()}</div>
        </Card>
        <Card className={styles.tabCard}>
          <Row style={{ margin: '16px 0' }}>
            <Col span={10} offset={0}>
              <Button
                type="primary"
                style={{ marginRight: '8px' }}
                onClick={() => router.push('/hrmanage/issueproof/add')}
              >
                <PlusOutlined style={{ fontSize: 12 }} />
                开证明
              </Button>
              <Button onClick={this.canceldeal} style={{ marginRight: '8px' }}>
                删除
              </Button>
              <Button onClick={this.outExcel} loading={excelLoading}>
                导出
              </Button>
            </Col>
          </Row>
          <StandardTable
            selectedRows={selectedRows}
            loading={loading}
            data={pageData}
            columns={columns}
            selectedRowKeys={selectedRowKeys}
            rowKey="proveSerHdlId"
            onSelectRow={this.handleSelectRows}
            onChange={this.handleStandardTableChange}
          />
        </Card>
      </PageHeaderWrapper>
    );
  }
}

export default IssueProve;
